﻿using Chaunce.FrameWork.NetCore.SysCore.Infrastructure.Attributes;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.PlatformAbstractions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Chaunce.Web.Core.Infrastructure.Swagger
{
    public class SwaggerRequiredFilter : IOperationFilter
    {

        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null || !operation.Parameters.Any())
            {
                return;
            }

            var requriedParameters = context.ApiDescription.ParameterDescriptions
                .Where(parameter => GetRequriedAttribute(parameter) != null)
                .Select(r => r.Name);
            if (requriedParameters.Count() == 0) return;
            foreach (var parameter in operation.Parameters)
            {
                if (requriedParameters.Contains(parameter.Name))
                {
                    parameter.Required = true;
                }
            }
        }

        private SwaggerRequiredAttribute GetRequriedAttribute(ApiParameterDescription parameter)
        {
            if (!(parameter.ModelMetadata is DefaultModelMetadata metadata) || metadata.Attributes.PropertyAttributes == null)
            {
                return null;
            }

            return metadata.Attributes.PropertyAttributes
                .OfType<SwaggerRequiredAttribute>()
                .FirstOrDefault();
        }

      
        private string ToCamelCase(string name)
        {
            return char.ToLowerInvariant(name[0]) + name.Substring(1);
        }
    }
}
